package chen.web.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 
 * @deprecated
 * @author chen
 *
 */
public abstract class AbstractHandler implements InvocationHandler {
	
	protected Object object;
	private Object objectProxy;
	
	public AbstractHandler(Object object){
		this.object = object;
		objectProxy = (Object)Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), this);
	}
	
	public Object getProxyObject(){
		return objectProxy;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
		// TODO Auto-generated method stub
		Object result = null;
		Operation operation = new Operation(method, args);
		operation.setStatus(Operation.OperationStatus.before);
		result = before(operation);
		if(result != null){
			return result;
		}
		try {
			result = method.invoke(object, args);
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			operation.setStatus(Operation.OperationStatus.exception);
			exception(operation);
			throw e.getTargetException();
		}
		operation.setStatus(Operation.OperationStatus.after);
		operation.setResult(result);
		Object result1 = after(operation);
		if(result1 != null){
			return result1;
		}
		
		return result;
	}
	
	protected abstract Object before(Operation operation);
	protected abstract Object after(Operation operation);
	protected abstract void exception(Operation operation);

}
